package com.store.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.store.dto.CartAddRequest;
import com.store.dto.CartUpdateRequest;
import com.store.entity.Cart;
import com.store.entity.Product;
import com.store.mapper.CartMapper;
import com.store.mapper.ProductMapper;
import com.store.vo.CartVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 购物车服务类
 */
@Service
@RequiredArgsConstructor
public class CartService {
    
    private final CartMapper cartMapper;
    private final ProductMapper productMapper;
    
    /**
     * 获取用户购物车列表
     */
    public List<CartVO> getCartList(Long userId) {
        return cartMapper.selectCartListByUserId(userId);
    }
    
    /**
     * 添加商品到购物车
     */
    @Transactional(rollbackFor = Exception.class)
    public void addToCart(Long userId, CartAddRequest request) {
        // 1. 检查商品是否存在
        Product product = productMapper.selectById(request.getProductId());
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        
        // 2. 检查商品是否上架
        if (product.getStatus() == null || product.getStatus() != 1) {
            throw new RuntimeException("商品已下架，无法添加到购物车");
        }
        
        // 3. 检查库存是否充足
        if (product.getStock() == null || product.getStock() < request.getQuantity()) {
            throw new RuntimeException("商品库存不足");
        }
        
        // 4. 检查购物车中是否已存在该商品
        Cart existCart = cartMapper.selectByUserIdAndProductId(userId, request.getProductId());
        
        if (existCart != null) {
            // 已存在，更新数量
            Integer newQuantity = existCart.getQuantity() + request.getQuantity();
            
            // 检查新数量是否超过库存
            if (newQuantity > product.getStock()) {
                throw new RuntimeException("购物车商品数量超过库存");
            }
            
            existCart.setQuantity(newQuantity);
            cartMapper.updateById(existCart);
        } else {
            // 不存在，新增记录
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setProductId(request.getProductId());
            cart.setQuantity(request.getQuantity());
            cartMapper.insert(cart);
        }
    }
    
    /**
     * 更新购物车商品数量
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCart(Long userId, CartUpdateRequest request) {
        // 1. 检查购物车记录是否存在
        Cart cart = cartMapper.selectById(request.getId());
        if (cart == null) {
            throw new RuntimeException("购物车记录不存在");
        }
        
        // 2. 检查是否是当前用户的购物车
        if (!cart.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作此购物车记录");
        }
        
        // 3. 检查商品库存
        Product product = productMapper.selectById(cart.getProductId());
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        
        if (product.getStock() == null || product.getStock() < request.getQuantity()) {
            throw new RuntimeException("商品库存不足");
        }
        
        // 4. 更新数量
        cart.setQuantity(request.getQuantity());
        cartMapper.updateById(cart);
    }
    
    /**
     * 删除购物车记录
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteCart(Long userId, Long cartId) {
        // 1. 检查购物车记录是否存在
        Cart cart = cartMapper.selectById(cartId);
        if (cart == null) {
            throw new RuntimeException("购物车记录不存在");
        }
        
        // 2. 检查是否是当前用户的购物车
        if (!cart.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作此购物车记录");
        }
        
        // 3. 删除记录
        cartMapper.deleteById(cartId);
    }
    
    /**
     * 清空用户购物车
     */
    @Transactional(rollbackFor = Exception.class)
    public void clearCart(Long userId) {
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, userId);
        cartMapper.delete(queryWrapper);
    }
    
    /**
     * 获取购物车商品数量
     */
    public Long getCartCount(Long userId) {
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, userId);
        return cartMapper.selectCount(queryWrapper);
    }
    
    /**
     * 批量删除购物车记录（用于结算后清除）
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(Long userId, List<Long> cartIds) {
        if (cartIds == null || cartIds.isEmpty()) {
            return;
        }
        
        // 验证所有记录都属于当前用户
        for (Long cartId : cartIds) {
            Cart cart = cartMapper.selectById(cartId);
            if (cart == null || !cart.getUserId().equals(userId)) {
                throw new RuntimeException("无权操作部分购物车记录");
            }
        }
        
        // 批量删除
        cartMapper.deleteBatchIds(cartIds);
    }
}


